
/**
 * 创建相机对象
 * @Author Fanxing
 * @param app  绑定div
 * @param width 宽度 （与app宽度相同
 * @param height 高度 （与app高度相同
 * @param type 没有类型，忽略。。不是相机前置或后置。。
 * ps: 扫码结果在 res.text里，方法是qrcode  获取拍照图片调用 getImg
 */
function camera(app, width, height, type) {
    let appObject = document.getElementById(app);
    let video = document.createElement("video");
    let span = document.createElement("span");
    let facingMode = 'environment';
    const codeReader = new ZXingBrowser.BrowserMultiFormatReader();
    video.style.width = width
    video.id = 'video'
    video.style.height = height
    video.autoplay = "autoplay";
    video.style.margin = 0;
    appObject.insertBefore(video, appObject.childNodes[0]);
    /**
     *  修改优先使用那颗摄像头，前置或后置
     * */
    this.setFacingMode = function(type) {
        // 前置摄像头：user 后置摄像头：environment
        facingMode = type;
    }
    this.establish = function establish() {
        let constraints = {
            video: {
                facingMode: facingMode,
                height: height,
                width: width
            },
            audio: false
        };
        let promise = navigator.mediaDevices.getUserMedia(constraints);
        promise.then(function(MediaStream) {
            video.srcObject = MediaStream;
            video.play();
        }).catch(function(PermissionDeniedError) {
            console.log(PermissionDeniedError);
        })
    }
    this.photograph = function photograph() {
        canvas = document.createElement("canvas");
        canvas.height = height;
        canvas.width = width;
        let ctx = canvas.getContext('2d');
        ctx.drawImage(video, 0, 0, width, height);
        return canvas;
    }
    // 解析码，获取解码的内容
    this.qrcode = function qrcode() {
        var promise = codeReader.decodeOnceFromVideoElement(video);
        // codeReader.decodeOnceFromVideoElement(video).then(function(res){
        // 	console.log("res:" + res)
        // 	return res;
        // })
        console.log(promise)
        return promise;
    }
    this.getImg = function getImg() {
        return this.photograph().toDataURL('image/jpeg')
    }
    this.close = function close() {
        this.MediaStreamTrack && this.MediaStreamTrack.stop();
    }
    // 开始疯狂扫码
    this.starcode = function starcode() {
        alert("在外部实现！！！")
    }
    //停止疯狂扫码
    this.stopcode = function stopcode() {
        alert("在外部实现！！！")
    }
}

